package yns.springboot.guide.demo.controller.data.mongodb;


import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Sorts;


@RestController
@RequestMapping("/mongodb/driver")
public class TestMongoDBDriverController {
	
	// http://localhost:8080/mongodb/driver
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private static final String MONGODB_DATABASE = "testdb";
	
	private static final String MONGODB_COLLECTION = "test";
	
	
	@Autowired
	private MongoClient mongoClient;
	
	@Autowired
	private MongoDatabase mongoDatabase;

	
	@GetMapping()
	public String testMongodb() {

		MongoDatabase database = mongoClient.getDatabase(MONGODB_DATABASE);
		MongoCollection<Document> collection = database.getCollection(MONGODB_COLLECTION);
		logger.info(collection.find().sort(Sorts.descending("_id")).first().toJson());
		
		MongoCollection<Document> collection2 = mongoDatabase.getCollection(MONGODB_COLLECTION);
		logger.info(collection2.find().sort(Sorts.descending("_id")).first().toJson());

		
		return "test.mongodb.driver";
	}
	

}
